package com.unittec.drainage.sdk.root.internal.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.unittec.drainage.sdk.root.common.FieldConstants;

public class SdkUtils {

    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String METHOD_POST = "POST";
    private static SSLContext ctx = null;
    private static HostnameVerifier verifier = null;
    private static SSLSocketFactory socketFactory = null;
    private static final char[] HEX_DIGITS;

    public static String toJSONString(Object obj) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        return JSON.toJSONString(obj, config, SerializerFeature.WriteDateUseDateFormat);
    }

    public static String toJSONString(Object obj, SerializerFeature... features) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        return JSON.toJSONString(obj, config, features);
    }

    public static String toJSON(Object obj) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        return JSON.toJSONString(obj, config);
        // temp = temp.replace(",\"code\":\"Success\",", ",\"code\":\"200\",").replace(",\"code\":\"Error\",",
        // ",\"code\":\"500\",");
        // temp.replace(",\"code\":\"SUCCESS\",", ",\"code\":\"200\",").replace(",\"code\":\"ERROR\",",
        // ",\"code\":\"500\",");
    }

    public static <T> T fromJson(String json, Class<T> t) {
        return JSON.parseObject(json, t);
    }

    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;

        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];

            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }

            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException var7) {
            var7.printStackTrace();
        } catch (IOException var8) {
            var8.printStackTrace();
        }

        return buffer;
    }

    private SdkUtils() {}

    private static HttpURLConnection getConnection(URL url) throws IOException {
        HttpURLConnection connection = null;
        if ("https".equals(url.getProtocol())) {
            HttpsURLConnection connHttps = (HttpsURLConnection)url.openConnection();
            connHttps.setSSLSocketFactory(socketFactory);
            connHttps.setHostnameVerifier(verifier);
            connection = connHttps;
        } else {
            connection = (HttpURLConnection)url.openConnection();
        }

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(60000);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("User-Agent", "core-sdk-java");
        return connection;
    }

    // 返回消息带鉴权的验证token
    public static String doPostJson2(String strURL, String json) throws IOException {
        BufferedReader reader = null;
        OutputStreamWriter out = null;

        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = getConnection(url);
            connection.connect();
            out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            out.append(json);
            out.flush();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));

            String line;
            StringBuilder res = new StringBuilder();
            for (; (line = reader.readLine()) != null; res.append(line)) {
            }

            String var8 = "";

            Map<String, List<String>> maps = connection.getHeaderFields();
            if (null != maps) {
                for (String key : maps.keySet()) {

                    if (FieldConstants.REQ_AUTHORIZATION.equalsIgnoreCase(key)) {
                        var8 = maps.get(key).get(0);
                        break;
                    }
                }
            }

            return res.toString() + FieldConstants.REQ_AUTHORIZATION + "===" + var8;
        } catch (IOException var12) {
            var12.printStackTrace();
            throw var12;
        } finally {
            if (reader != null) {
                reader.close();
            }

            if (out != null) {
                out.close();
            }
        }
    }

    public static String doPostJson(String strURL, String json) throws IOException {
        BufferedReader reader = null;
        OutputStreamWriter out = null;

        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = getConnection(url);
            connection.connect();
            out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            out.append(json);
            out.flush();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));

            String line;
            StringBuilder res = new StringBuilder();
            for (; (line = reader.readLine()) != null; res.append(line)) {
            }

            return res.toString();
        } catch (IOException var12) {
            var12.printStackTrace();
            throw var12;
        } finally {
            if (reader != null) {
                reader.close();
            }

            if (out != null) {
                out.close();
            }

        }
    }

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);

        for (int j = 0; j < len; ++j) {
            buf.append(HEX_DIGITS[bytes[j] >> 4 & 15]);
            buf.append(HEX_DIGITS[bytes[j] & 15]);
        }

        return buf.toString();
    }

    public static String encode(String str) {
        if (str == null) {
            return null;
        } else {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
                messageDigest.update(str.getBytes());
                return getFormattedText(messageDigest.digest());
            } catch (Exception var2) {
                throw new RuntimeException(var2);
            }
        }
    }

    public static boolean isEmpty(String value) {
        int strLen;
        if (value != null && (strLen = value.length()) != 0) {
            for (int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(value.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    public static String getResultId() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        SecureRandom random = new SecureRandom();
        int randint = random.nextInt();
        if (randint < 0) {
            randint = -1 * randint;
        }

        return format.format(new Date()) + randint;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(SdkUtils.getResultId());
        }

        ConcurrentHashMap<String, String> map = new ConcurrentHashMap();
        map.putIfAbsent("123", "123");
        map.putIfAbsent("123", "abc");
        map.putIfAbsent("123", "345");
        System.out.println(map);

    }

    public static boolean isNull(Object obj) {
        return null == obj;
    }

    public static boolean isNotNull(Object obj) {
        return !isNull(obj);
    }

    static {
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] {new SdkUtils.DefaultTrustManager()}, new SecureRandom());
            ctx.getClientSessionContext().setSessionTimeout(15);
            ctx.getClientSessionContext().setSessionCacheSize(1000);
            socketFactory = ctx.getSocketFactory();
        } catch (Exception var1) {
        }

        verifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return false;
            }
        };
        HEX_DIGITS = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    }

    private static class DefaultTrustManager implements X509TrustManager {
        private DefaultTrustManager() {}

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
    }
}
